package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import com.sun.javafx.collections.MappingChange;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_KEY_PRE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userServiceImpl;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key = FOLLOW_KEY_PRE + userId;

        // 1.判断到底是关注还是取关
        if(isFollow){
            // 2.关注，新增数据
            // 2.1.数据库数据新增
            Follow follow = new Follow(); //关注关系对象
            follow.setFollowUserId(followUserId); //设置博主id
            follow.setUserId(userId); //设置关注用户的id
            follow.setCreateTime(LocalDateTime.now());
            boolean isSuccess = save(follow);
            // 2.2.Redis新增用户关注数据
            if(isSuccess){
                // SADD ..:userId followUserId
                stringRedisTemplate.opsForSet().add(key,followUserId.toString());
            }
        }else{
            // 3.取关，删除数据 delete from tb_follow where user_id = ? and follow_user_id = ?
            QueryWrapper<Follow> qw = new QueryWrapper<>();
            qw
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId);

            boolean isSuccess = remove(qw);
            // 在Redis中把当前用户关注的followUserId删除
            if(isSuccess){
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();

        // 1.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        QueryChainWrapper<Follow> eq = query()
                .eq("user_id", userId)
                .eq("follow_user_id", followUserId);
        Integer count = eq.count();
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(Long userId) {
        // 1.获取当前用户
        Long curId = UserHolder.getUser().getId();
        String key1 = FOLLOW_KEY_PRE + curId;
        // 2.求交集
        String key2 = FOLLOW_KEY_PRE + userId;
        // 2.1.得到两个用户交集的用户id字符串集合
        Set<String> userIdList = stringRedisTemplate.opsForSet().intersect(key1, key2);
        // 判断集合是否为空
        if(userIdList == null || userIdList.isEmpty()){
            //无交集，返回空集
            return Result.ok(Collections.emptyList());
        }
        // 3.解析id集合，利用stream流将字符串集合转换成Long集合
        List<Long> userIds = userIdList.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4.集合，将User集合转换成UserDTO 集合
        List<UserDTO> userDTOs = userServiceImpl.listByIds(userIds)
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        // 5.返回
        return Result.ok(userDTOs);
    }

    @Override
    public Result countOfFollows() {
        // 1.获取当前用户信息
        Long userId = UserHolder.getUser().getId();
        // 2.查询当前用户的关注者人数
        Long size = stringRedisTemplate.opsForSet().size(FOLLOW_KEY_PRE + userId);
        if (size == null || size == 0){
            return Result.ok(0);
        }
        return Result.ok(size);
    }

    @Override
    public Result infoOfFollows() {
        // 1.获取当前用户信息
        Long userId = UserHolder.getUser().getId();
        // 2.查询当前用户的关注者，返回一个userId集合(随机返回3个)
//        Set<String> ids_str = stringRedisTemplate.opsForSet().members(FOLLOW_KEY_PRE + userId);
        List<String> ids_str = stringRedisTemplate.opsForSet().randomMembers(FOLLOW_KEY_PRE + userId, 3L);
        if(ids_str == null || ids_str.isEmpty()){
            //如果没有关注者，返回空集合
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = ids_str.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3.根据userId集合查询数据库，将UserDTO存入集合
        List<UserDTO> list = new ArrayList<>(ids.size());
        List<User> users = userServiceImpl.listByIds(ids);
        for (User user: users){
            UserDTO userDTO = new UserDTO();
            userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            list.add(userDTO);
        }
        // 4.返回关注者集合
        return Result.ok(list);
    }
}
